package br.ucb.cesbdao.janelas;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.regex.PatternSyntaxException;

import javax.swing.AbstractListModel;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.TableRowSorter;

import org.apache.log4j.Logger;

import br.ucb.cesbdao.beans.Pessoa;
import br.ucb.cesbdao.enuns.EnumLabelAndBotao;
import br.ucb.cesbdao.enuns.EnumMensagens;
import br.ucb.cesbdao.enuns.EnumResources;
import br.ucb.cesbdao.enuns.EnumTipoAtendimento;
import br.ucb.cesbdao.enuns.EnumTitulo;
import br.ucb.cesbdao.model.AtendidoModel;
import br.ucb.cesbdao.model.PessoaModel;
import br.ucb.cesbdao.model.impl.AtendidoModelImpl;
import br.ucb.cesbdao.model.impl.PessoaModelImpl;
import br.ucb.cesbdao.modeloTabelas.ModeloTabelaPacienteApoio;
import br.ucb.cesbdao.servicos.Servicos;
import br.ucb.cesbdao.utilBeans.AtendimentoUtil;
import br.ucb.cesbdao.utilBeans.PessoaUtil;
import br.ucb.cesbdao.visao.Visao;

@SuppressWarnings("serial")
public class JanelaNovoAtendimeto extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTable tbAtendido;
	private JTextField txtNomeAtendido;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JRadioButton rdbtnMasculino;
	private JRadioButton rdbtnFeminino;
	private JButton btnNovoAtendido;
	@SuppressWarnings("rawtypes")
	private JList jlistTipo;
	private JButton btnOk;
	private JButton btnCancelar;
	private JLabel lblSexo;
	private JScrollPane spAtendido;
	private Pessoa atendido;
	private ModeloTabelaPacienteApoio modeloTablePaciente = new ModeloTabelaPacienteApoio();
	static Logger logger = Servicos.carregaLog(JanelaNovoAtendimeto.class);

	/**
	 * Create the dialog.
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JanelaNovoAtendimeto() {
		setTitle(EnumTitulo.TITULO_NOVO_ATENDIMENTO.getTitulo());
		setModal(true);
		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setLocationRelativeTo(null);
		setBounds(100, 100, 542, 353);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);

		spAtendido = new JScrollPane();

		txtNomeAtendido = new JTextField();
		txtNomeAtendido.setColumns(10);
		txtNomeAtendido.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				txtNomeAtendido.setText(txtNomeAtendido.getText().toUpperCase());
				zeraPreencheTabelaPessoa();
			}
		});

		JLabel lblAtendido = new JLabel(EnumLabelAndBotao.ATENDIDO.getTexto());

		rdbtnMasculino = new JRadioButton(EnumLabelAndBotao.MASCULINO.getTexto());
		buttonGroup.add(rdbtnMasculino);

		rdbtnFeminino = new JRadioButton(EnumLabelAndBotao.FEMININO.getTexto());
		buttonGroup.add(rdbtnFeminino);

		lblSexo = new JLabel(EnumLabelAndBotao.SEXO.getTexto());

		btnNovoAtendido = new JButton(EnumLabelAndBotao.NOVO_ATENDIDO.getTexto());
		btnNovoAtendido.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				StringBuilder erro = new StringBuilder();

				if(txtNomeAtendido.getText().trim().isEmpty())
					erro.append("Nome invalido \n");

				if(buttonGroup.getSelection() == null)
					erro.append("Sexo invalido"); 


				if(erro.length() != 0){
					Visao.showMessageError(erro.toString(),"Erro");
					return;
				}
				PessoaModel model = new PessoaModelImpl();
				
				setAtendido(PessoaUtil.novaPessoa(txtNomeAtendido.getText(),rdbtnMasculino.isSelected() ? 'M' : 'F'));
				model.addPessoa(getAtendido());
				zeraPreencheTabelaPessoa();
			}
		});
		btnNovoAtendido.setIcon(new ImageIcon(JanelaNovoAtendimeto.class.getResource(EnumResources.ICONE_ADICIONAR.getCaminho())));

		jlistTipo = new JList();
		jlistTipo.setModel(new AbstractListModel() {
			public int getSize() {
				return EnumTipoAtendimento.values().length;
			}
			public Object getElementAt(int index) {
				return EnumTipoAtendimento.getByIndex(index);
			}
		});
		
		jlistTipo.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), EnumTitulo.TITULO_TIPO.getTitulo(), TitledBorder.LEADING, TitledBorder.ABOVE_TOP, null, new Color(0, 0, 0)));
		jlistTipo.setBackground(SystemColor.menu);

		btnOk = new JButton(EnumLabelAndBotao.OK.getTexto());
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(AtendimentoUtil.novoAtendimentoChegadaGerencia(tbAtendido, modeloTablePaciente, jlistTipo))
					dispose();

			}
		});
		btnOk.setIcon(new ImageIcon(JanelaNovoAtendimeto.class.getResource(EnumResources.ICONE_SALVAR.getCaminho())));

		btnCancelar = new JButton("Cancelar");
		btnCancelar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		});
		btnCancelar.setIcon(new ImageIcon(JanelaNovoAtendimeto.class.getResource(EnumResources.ICONE_CANCELAR.getCaminho())));
		GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
		gl_contentPanel.setHorizontalGroup(
				gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_contentPanel.createSequentialGroup()
										.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
												.addGroup(gl_contentPanel.createSequentialGroup()
														.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
																.addComponent(lblAtendido)
																.addComponent(lblSexo))
																.addGap(18)
																.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
																		.addComponent(txtNomeAtendido, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)
																		.addGroup(gl_contentPanel.createSequentialGroup()
																				.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
																						.addComponent(rdbtnFeminino)
																						.addComponent(rdbtnMasculino))
																						.addGap(18)
																						.addComponent(btnNovoAtendido))))
																						.addGroup(gl_contentPanel.createSequentialGroup()
																								.addComponent(spAtendido, GroupLayout.PREFERRED_SIZE, 378, GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
																								.addComponent(jlistTipo, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE)))
																								.addContainerGap())
																								.addGroup(Alignment.TRAILING, gl_contentPanel.createSequentialGroup()
																										.addComponent(btnOk)
																										.addPreferredGap(ComponentPlacement.RELATED)
																										.addComponent(btnCancelar)
																										.addGap(152))))
				);
		gl_contentPanel.setVerticalGroup(
				gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblAtendido)
								.addComponent(txtNomeAtendido, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_contentPanel.createSequentialGroup()
												.addGap(32)
												.addComponent(lblSexo))
												.addGroup(gl_contentPanel.createSequentialGroup()
														.addGap(18)
														.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
																.addComponent(btnNovoAtendido)
																.addGroup(gl_contentPanel.createSequentialGroup()
																		.addComponent(rdbtnMasculino)
																		.addPreferredGap(ComponentPlacement.RELATED)
																		.addComponent(rdbtnFeminino)))))
																		.addGap(18)
																		.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
																				.addComponent(jlistTipo, GroupLayout.PREFERRED_SIZE, 122, GroupLayout.PREFERRED_SIZE)
																				.addComponent(spAtendido, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE))
																				.addPreferredGap(ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
																				.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING, false)
																						.addComponent(btnOk, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
																						.addComponent(btnCancelar))
																						.addContainerGap())
				);

		tbAtendido = new JTable();
		tbAtendido.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tbAtendido.setModel(modeloTablePaciente);
		AtendidoModel model = new AtendidoModelImpl();
		modeloTablePaciente.setPacientes(model.consultaPaciente());
		spAtendido.setViewportView(tbAtendido);
		contentPanel.setLayout(gl_contentPanel);
		
	}


	public Pessoa getAtendido() {
		return atendido;
	}


	public void setAtendido(Pessoa atendido) {
		this.atendido = atendido;
	}

	public void zeraPreencheTabelaPessoa() {
		AtendidoModel model = new AtendidoModelImpl();
		if(txtNomeAtendido.getText().equalsIgnoreCase("")){
			modeloTablePaciente = new ModeloTabelaPacienteApoio();
			tbAtendido.setModel(modeloTablePaciente);
			modeloTablePaciente.setPacientes(model.consultaPaciente());
			return;
		}
		modeloTablePaciente = new ModeloTabelaPacienteApoio();
		tbAtendido.setModel(modeloTablePaciente);
		tbAtendido.getTableHeader().setReorderingAllowed(false);
		tbAtendido.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tbAtendido.setAutoCreateRowSorter(true);
		modeloTablePaciente.setPacientes(model.consultaPacienteByNome(txtNomeAtendido.getText()));
		filtraTabelaAtendido();

	}
	public void filtraTabelaAtendido() {
		TableRowSorter<ModeloTabelaPacienteApoio> sorter = new TableRowSorter<ModeloTabelaPacienteApoio>(modeloTablePaciente);
		String busca = txtNomeAtendido.getText();
		tbAtendido.setRowSorter(sorter);

		if (busca.length() == 0)
			sorter.setRowFilter(null);
		else{
			try{
				sorter.setRowFilter(RowFilter.regexFilter("(?i)"+busca,0));
			}catch (PatternSyntaxException ex) {
				logger.error(ex.getMessage());
				Visao.showMessageWarning(EnumMensagens.MSG_ALERTA_FILTRAR.getMensagem(), "Aviso do Sistema");
			}
		}
	}
}
